package com.baizhi.service;

import com.baizhi.dao.ProductMapper;
import com.baizhi.entity.Picture;
import com.baizhi.entity.Product;
import com.baizhi.entity.ProductExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService{

    @Resource
    private ProductMapper productMapper;

    @Autowired
    private PictureService pictureService;

    @Override
    public List<Product> showAll(String type) {
        ProductExample productExample = new ProductExample();

        productExample.createCriteria().andTypeEqualTo(type);
        return productMapper.selectByExample(productExample);
    }

    @Override
    public List<Product> findAll() {
        ProductExample productExample = new ProductExample();

        return productMapper.selectByExample(productExample);
    }

    @Override
    public Product findById(String id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(Product product) {
        product.setId(UUID.randomUUID().toString());
        product.setStatus(0);
        product.setCreatedate(new Date());
        productMapper.insert(product);
    }

    @Override
    public void update(Product product) {
        productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public void delete(String id) {
        productMapper.deleteByPrimaryKey(id);
        List<Picture> byId = pictureService.findById(id);
        for (Picture picture : byId) {
            pictureService.delete(picture.getId());
        }
    }
}
